<template>
  <div class="selectionSupermarketChild">
    <searchrevealing>
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="98px">
        <el-form-item label="商品名称" prop="styleCode">
          <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable style="width: 220px" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="类目" prop="category">
          <el-cascader ref="categoryRef" v-model="queryParams.category" :props="categoryProps" @change="handleChange"
            style="width: 220px" placeholder="请选择类目" />
        </el-form-item>
        <el-form-item label="是否机制" prop="mechanism">
          <el-select v-model="queryParams.mechanism" placeholder="请选择是否机制" clearable style="width: 220px">
            <el-option v-for="dict in mechanismList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="款式编码" prop="styleCode">
          <el-input v-model="queryParams.styleCode" placeholder="请输入款式编码" clearable style="width: 220px" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-select-v2 v-model="queryParams.supplierName" filterable clearable :options="supplierNameOptions"
            placeholder="请选择供应商" style="width: 220px" />
          <!-- <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" style="width: 220px"></el-input> -->
        </el-form-item>
        <el-form-item label="库存状态" prop="kucun">
          <el-select v-model="queryParams.kucun" placeholder="请选择库存状态" clearable style="width: 220px">
            <el-option v-for="dict in kuncunList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="选品部门" prop="department">
          <el-select v-model="queryParams.department" placeholder="请选择选品部门" clearable style="width: 220px">
            <el-option v-for="dict in departmentList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商家款式编码" prop="businesSstyleName">
          <el-input v-model="queryParams.businesSstyleName" placeholder="请输入款式编码" clearable style="width: 220px" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="商家款式名称" prop="businesStyleCode">
          <el-input v-model="queryParams.businesStyleCode" placeholder="请输入款式编码" clearable style="width: 220px" @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </searchrevealing>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="">商品预约</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="secondmentApprovals">借调审批</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="selectionSupermarketChildList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="招商人" align="center" prop="recruiter" />
        <el-table-column label="商品名称" align="center" prop="styleName" />
        <el-table-column label="商品编码" align="center" prop="styleCode" />
        <el-table-column label="商品主图" align="center" prop="productImage" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.productImage" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="类目" align="center" prop="categoryName" />
        <el-table-column label="品牌" align="center" prop="brand">
          <template #default="scope">
            {{ handleFilterBrand(scope.row.brand, brandList) }}
          </template>
        </el-table-column>
        <el-table-column label="选品部门" align="center" prop="anchor" />
        <el-table-column label="直播机制" align="center" prop="liveStreamingMechanism" />
        <el-table-column label="商品卖点" align="center" prop="sellingPoints" />
        <el-table-column label="佣金" align="center" prop="commission" />
        <el-table-column label="售卖次数" align="center" prop="salesFrequency" />
        <el-table-column label="售卖主播" align="center" prop="sellingAnchors" />
        <el-table-column label="库存数量" align="center" prop="inventory" />
        <el-table-column label="能否破价" align="center" prop="discountPrice" />
        <el-table-column label="成本价" align="center" prop="costPrice" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleInfo(scope.row)" class="color_theme">
              查看详情</el-button>
            <el-button link type="primary" @click="selectionRecord(scope.row)" class="color_theme"
              style="margin-left: 0px !important">
              选品记录</el-button>
            <el-button :disabled="!scope.row.inventory" link type="primary" @click="secondmentsChange(scope.row)"
              class="color_theme" style="margin-left: 0px !important">
              商品借调</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!--商品详情抽屉 -->
    <commoditydetails @doClose="commoditydetailsClose" :commoditydetailsData="commoditydetailsData"
      :dialogInfoVisible="dialogInfoVisible"></commoditydetails>
    <!-- 选品记录 -->
    <selectionRecords @doClose="selectionRecordClose" :selectionRecordData="selectionRecordData"
      :selectionRecordVisible="selectionRecordVisible"></selectionRecords>
    <!-- 商品借调 -->
    <secondments @doClose="secondmentsClose" :secondmentsData="secondmentsData"
      :secondmentsVisible="secondmentsVisible">
    </secondments>
    <!-- 借调审批 -->
    <secondmentApproval @doClose="secondmentApprovalClose" :secondmentApprovalVisible="secondmentApprovalVisible"
      v-if="secondmentApprovalVisible">
    </secondmentApproval>
  </div>

</template>
<script setup name="SelectionSupermarketChild" lang="ts">
import selectionRecords from './selectionRecord.vue'
import secondments from './secondments.vue'
import secondmentApproval from './secondmentApproval.vue'
import { BrandVO } from '@/api/system/brand/types';
import { listBrand } from '@/api/system/brand';
import commoditydetails from '../../components/commoditydetails.vue'
import { hmSupplierList } from '@/api/group/supplier/index'
import { listSupplierAddProduct, getSupplierAddProducts, getproductscategorychildlistbypid } from '@/api/system/supplierAddProducts';
import { SelectionSupermarketQueryParams, SelectionSupermarketVO, SelectionRecordVO, SecondmentsVO } from '@/api/group/selectionSupermarket/types'
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const ids = ref<Array<string | number>>([]);
const brandList = ref<BrandVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const selectionSupermarketChildList = ref<SelectionSupermarketVO[]>([]);
const categoryRef = ref();
const supplierNameOptions = ref<any[]>([])

const dialogInfoVisible = ref(false)
const commoditydetailsData = ref<SelectionSupermarketVO>()

const selectionRecordVisible = ref(false)
const selectionRecordData = ref<SelectionRecordVO>()

const secondmentsVisible = ref(false)
const secondmentsData = ref<SecondmentsVO>()

const secondmentApprovalVisible = ref(false)

const queryParams = ref<SelectionSupermarketQueryParams>({
  pageNum: 1,
  pageSize: 10,
  auditStatus: undefined,
  styleName: undefined,
  category: undefined,
  firstCategory: undefined,
  secondCategory: undefined,
  thirdCategory: undefined,
  fourthCategory: undefined,
  mechanism: undefined,
  styleCode: undefined,
  supplierName: undefined,
  kucun: undefined,
  department: undefined,
  businesSstyleName: undefined,
  businesStyleCode: undefined,
})

const mechanismList = ref([
  { label: '测试机制： 是', value: '1', },
  { label: '测试机制： 否', value: '0', }
])
const kuncunList = reactive([
  { label: '测试库存状态1', value: '1' },
  { label: '测试库存状态2', value: '2' },
])
const departmentList = reactive([
  { label: '测试选品部门1', value: '1' },
  { label: '测试选品部门2', value: '2' },
])
/**
 * 获取供应商列表
 */
 const getHmSupplierList = async() =>{
    const res = await hmSupplierList()
    supplierNameOptions.value = res.rows.map((item: any)=>(
        {
            label: item.supplierName,
            value: item.userId
        }
    ))
}
/** 借调审批 */
const secondmentApprovals = () => {
  secondmentApprovalVisible.value = true
}
/** 借调审批关闭 */
const secondmentApprovalClose = () => {
  secondmentApprovalVisible.value = false
}
/** 查看商品详情 */
const handleInfo = (row?: SelectionSupermarketVO) => {
  nextTick(async () => {
    const _id = row?.id || ids.value[0];
    const res: any = await getSupplierAddProducts(_id);
    dialogInfoVisible.value = true;
    commoditydetailsData.value = res.data
  });
};
/** 商品详情关闭 */
const commoditydetailsClose = () => {
  dialogInfoVisible.value = false;
}
/** 选品记录 */
const selectionRecord = async (row?: SelectionSupermarketVO) => {
  const _id = row?.id || ids.value[0];
  const res: any = await getSupplierAddProducts(_id);
  selectionRecordVisible.value = true
  selectionRecordData.value = res.data
};
/** 选品记录关闭 */
const selectionRecordClose = () => {
  selectionRecordVisible.value = false;
}
/** 商品借调 */
const secondmentsChange = async (row?: SelectionSupermarketVO) => {
  const _id = row?.id || ids.value[0];
  const res: any = await getSupplierAddProducts(_id);
  secondmentsVisible.value = true
  secondmentsData.value = Object.assign(res.data, {
    datas: [
      { id: '0', choosePerson: '测试', choosePersonTimes: '测试', sellingFlag: '否', inventory: 111 },
      { id: '1', choosePerson: '测试', choosePersonTimes: '测试', sellingFlag: '否', inventory: 222 }
    ]
  })
};
/**商品借调关闭 */
const secondmentsClose = () => {
  secondmentsVisible.value = false;
}

/**
 * 获取品牌信息
 */
const getListBrand = async () => {
  const res = await listBrand()
  brandList.value = res.rows;
}
/**
/**
 * 品牌检索value
 * @param para 
 * @param dict 
 */
const handleFilterBrand = (para: string | number | undefined, dict: Array<any>) => {
  let _label = '';
  dict.forEach((item: any) => {
    if (item.id == String(para)) {
      _label = item.brandName;
    }
  });
  return _label;
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SelectionSupermarketVO[]) => {
  ids.value = selection.map((item) => item.id);
};
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
  if (val) {
    categoryRef.value.togglePopperVisible()
    queryParams.value.category = val[val.length - 1]
    queryParams.value.firstCategory = val[0]
    queryParams.value.secondCategory = val[1]
    queryParams.value.thirdCategory = val[2]
    queryParams.value.fourthCategory = val[3]
  }
}

// 类目请求方法封装
const ategoryQuest = (pid: string | number, level: any, resolve: (data: any) => void) => {
  getproductscategorychildlistbypid({ pid: pid }).then(res => {
    const datas = res.rows.map((value: { categoryId: string, categoryName: string }) => ({
      value: value.categoryId,
      label: value.categoryName,
      // leaf: level >= 3
    }));
    resolve(datas);
  })
}
// 类目props
const categoryProps = reactive({
  lazy: true,
  checkStrictly: true,
  lazyLoad(node: any, resolve: (data: any) => void) {
    const { level } = node
    const pid = !level ? 0 : node.value
    ategoryQuest(pid, level, resolve)
  }
})
/** 查询供应商添加商品列表 */
const getList = async () => {
  try {
    loading.value = true;
    const res = await listSupplierAddProduct(queryParams.value);
    selectionSupermarketChildList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch (e) {
  } finally {
    loading.value = false;
  }
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.auditStatus = '1,2,3,4,5,6,7,8,9';
  handleQuery();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
onMounted(() => {
  queryParams.value.auditStatus = '1,2,3,4,5,6,7,8,9';
  queryParams.value.pageNum = 1;
  getHmSupplierList();
  getListBrand();
  getList();
});

</script>
